package com.xingkeduo.business.user.domain;

import com.alibaba.fastjson.JSON;
import com.xingkeduo.business.user.event.EventHandleService;
import com.xingkeduo.business.user.event.MsgTempDTO;
import com.xingkeduo.business.user.feign.MarketingFeignService;
import com.xingkeduo.business.user.feign.OrderService;
import com.xingkeduo.business.user.service.*;
import com.xingkeduo.pojo.dto.*;
import com.xingkeduo.pojo.enums.*;
import com.xingkeduo.pojo.query.*;
import com.xingkeduo.pojo.table.*;
import com.xingkeduo.pojo.utils.Base64Utils;
import com.xingkeduo.pojo.utils.RandomNumberUtil;
import com.xingkeduo.pojo.utils.ResponseUtils;
import com.xingkeduo.util.pojo.base.BaseTable;
import com.xingkeduo.util.pojo.domain.Page;
import com.xingkeduo.util.pojo.enums.SexEnum;
import com.xingkeduo.util.pojo.enums.YesNoEnum;
import com.xingkeduo.util.pojo.exception.BusinessException;
import com.xingkeduo.util.pojo.exception.DataException;
import com.xingkeduo.util.pojo.exception.InputParamException;
import com.xingkeduo.util.tool.CommonUtil;
import com.xingkeduo.util.tool.IdentityUtil;
import com.xingkeduo.util.tool.IdentityUtil.Worker;
import com.xingkeduo.util.tool.RegularUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Author:gaozifeng
 * @Date 2019/2/18 18:50
 **/
@Component
public class ConsumerDomain {

    private static Logger log = LoggerFactory.getLogger(ConsumerDomain.class);

    @Resource
    private ConsumerService consumerService;
    @Resource
    private ConsumerStatisticsService consumerStatisticsService;
    @Resource
    private ConsumerPrivateService consumerPrivateService;
    @Resource
    private ConsumerRelateService relateService;
    @Resource
    private ConsumerFileService consumerFileService;
    @Resource
    private FeignDomain feignDomain;
    @Resource
    private ConsumerStyleService consumerStyleService;
    @Resource
    private ConsumerSmsService consumerSmsService;
    @Resource
    private OrderService orderService;
    @Resource
    private MarketingFeignService marketingFeignService;
    @Resource
    private ShareReceiveService shareReceiveService;
    @Resource
    private EventHandleService eventHandleService;
    //    @Resource(name = "redisDao")
//    private CacheDao<?, ?> cacheDao;
    private static int initListSize = 8;
    private static int addInt = 1;


    private static final String INVITE_PRE = "您邀请的好友";
    private static final String INVITE_SUF = "已经服务完成，感谢您的邀请，优惠券已放入您的账户，赶紧下单使用吧！";

    /**
     * 查询用户信息 小程序
     *
     * @param f_user_id:
     * @param time:
     * @param token:
     * @param mobile_type:
     * @return : java.lang.String
     * @author : pantong
     * @date : 2019/4/15 20:22
     */
    public Map<String, Object> getUserInfo(long f_user_id, String time, String token, String mobile_type) throws Throwable {
//        ConsumerTO consumerTO = consumerService.selectByPrimary(f_user_id);
//        if (null == consumerTO || consumerTO.getId() <= 0) {
//            throw new DataException(DataException.Type.DEFAULT, "用户不存在");
//        }
        if (0L == f_user_id && StringUtils.isBlank(mobile_type)) {
            throw new DataException(DataException.Type.DEFAULT, "参数不能为空");
        }
        //手机号
        ConsumerTO consumerTO = null;
        ConsumerPrivateTO privateTO = consumerPrivateService.selectByPrimary(f_user_id);
        if (null != privateTO) {
            if (StringUtils.isNotBlank(privateTO.getPhone())) {
                ConsumerPrivateQO privateQO = new ConsumerPrivateQO();
                privateQO.setPhone(privateTO.getPhone()).setIsDelete(YesNoEnum.NO);
                List<Long> list = consumerPrivateService.selectUserPrivateForId(privateQO);
                if (list.size() >= 1) {
                    List<ConsumerTO> consumerList = consumerService.selectConsumerList(new ConsumerQO().setIds(list).setIsDelete(YesNoEnum.NO));
                    for (ConsumerTO consumer : consumerList) {
                        //TODO 以后增加用户渠道 需要更改
                        if (("wechat".equals(mobile_type) || "weapp".equals(mobile_type)) && consumer.getType() == UserTypeEnums.WX.getType()) {
                            consumerTO = consumer;
                            break;
                        }
                        if ("alipay".equals(mobile_type) && consumer.getType() == UserTypeEnums.ALI.getType()) {
                            consumerTO = consumer;
                            break;
                        }
                    }
                }
            } else {
                consumerTO = consumerService.selectByPrimary(f_user_id);
            }
        }

        if (null == consumerTO) {
            throw new DataException(DataException.Type.DEFAULT, "用户不存在");
        }

        //昵称
        Map<String, Object> map = new HashMap<String, Object>();
        if (privateTO != null) {
            map.put("mobile", StringUtils.isEmpty(privateTO.getPhone()) ? "" : privateTO.getPhone());
            map.put("f_sex", privateTO.getSex() == null ? -1 : privateTO.getSex().getValue());
        }
        map.put("f_name", StringUtils.isEmpty(consumerTO.getName()) ? "" : Base64Utils.decoderParam(consumerTO.getName()));
        //头像
        ConsumerFileQO consumerFileQO = new ConsumerFileQO();
        consumerFileQO.setConsumerId(consumerTO.getId());
        consumerFileQO.setIsDelete(YesNoEnum.NO);
        List<ConsumerFileTO> consumerFileTOList = consumerFileService.selectConsumerFileList(consumerFileQO);
        if (consumerFileTOList != null && consumerFileTOList.size() > 0) {
            map.put("f_avatar", StringUtils.isEmpty(consumerFileTOList.get(0).getPath()) ? "" : consumerFileTOList.get(0).getPath());
        }
        //服务次数 距离最后一次服务的天数
        try {
            ResponseUtils responseUtils = orderService.queryServices(String.valueOf(consumerTO.getId()), "1");
            if (responseUtils.success()) {
                Map serviceMap = (Map) responseUtils.getData();
                map.put("days", serviceMap.get("serviceDays"));
                map.put("count", serviceMap.get("serviceTimes"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("days", 0);
            map.put("count", 0);
        }

        //获取用户快到期的券数量及是否有未认证的卡
        try {
            ResponseMessage responseMessage = marketingFeignService.getUserCardAuthInfo(consumerTO.getId(), "1");
            log.info("ConsumerDomain.getUserInfo 获取用户快到期的券数量及是否有未认证的卡接口返回信息：" + responseMessage == null ? "" : (responseMessage.getData() == null ? "" : responseMessage.getData().toString()));
            if (responseMessage.getStatus() == 1 && responseMessage.getData() != null && StringUtils.isNotEmpty(responseMessage.getData().toString())) {
                Map mapTypes = (Map) responseMessage.getData();
                Integer cardCount = mapTypes.get("cardCount") == null ? 0 : Integer.valueOf(mapTypes.get("cardCount").toString());
                Boolean couponCountFlag = mapTypes.get("couponCount") == null ? false : (Integer.valueOf(mapTypes.get("couponCount").toString()) > 0);
                map.put("coupon_count", cardCount);
                map.put("has_no_cert", couponCountFlag);
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("coupon_count", 0);
            map.put("has_no_cert", false);
        }

        return map;
    }


    /**
     * 查询用户基本信息（头像、昵称）
     *
     * @param f_user_id:
     * @param time:
     * @param token:
     * @param mobile_type:
     * @return : java.lang.String
     * @throws Throwable
     * @author : pantong
     * @date : 2019/4/15 20:22
     */
    public Map<String, Object> getBasicUserInfo(long f_user_id, String time, String token, String mobile_type) throws Throwable {
        //昵称
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("f_name", "");
        map.put("f_avatar", "");

        ConsumerTO consumerTO;
        try {
            consumerTO = consumerService.selectByPrimary(f_user_id);
        } catch (Throwable e) {
            e.printStackTrace();
            return map;
        }
        if (null == consumerTO || consumerTO.getId() <= 0) {
            return map;
        }

        map.put("f_name", StringUtils.isEmpty(consumerTO.getName()) ? "" : Base64Utils.decoderParam(consumerTO.getName()));

        //头像
        ConsumerFileQO consumerFileQO = new ConsumerFileQO();
        consumerFileQO.setConsumerId(f_user_id);
        consumerFileQO.setIsDelete(YesNoEnum.NO);
        List<ConsumerFileTO> consumerFileTOList;
        try {
            consumerFileTOList = consumerFileService.selectConsumerFileList(consumerFileQO);
        } catch (Exception e) {
            e.printStackTrace();
            return map;
        }
        if (consumerFileTOList != null && consumerFileTOList.size() > 0) {
            map.put("f_avatar", StringUtils.isEmpty(consumerFileTOList.get(0).getPath()) ? "" : consumerFileTOList.get(0).getPath());
        }

        return map;
    }


    /**
     * 查询用户标签设置项
     *
     * @param f_user_id:
     * @param time:
     * @param token:
     * @param mobile_type:
     * @return : java.lang.String
     * @throws Throwable
     * @author : pantong
     * @date : 2019/4/15 20:22
     */
    public Map<String, Object> revise_set(long f_user_id, String time, String token, String mobile_type) throws Throwable {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("f_sex", "");
        map.put("tag_year", "");
        map.put("tag_feel_style", "");
        map.put("tag_job", "");
        map.put("arrive_store_distance", "");

        ConsumerTO consumerTO;
        try {
            consumerTO = consumerService.selectByPrimary(f_user_id);
        } catch (Throwable e) {
            e.printStackTrace();
            return map;
        }
        if (null == consumerTO || consumerTO.getId() <= 0) {
            return map;
        }

        ConsumerPrivateTO privateTO = consumerPrivateService.selectByPrimary(consumerTO.getId());
        if (privateTO != null) {
            if (SexEnum.FEMALE.equals(privateTO.getSex())) {
                map.put("f_sex", "女");
            } else if (SexEnum.MALE.equals(privateTO.getSex())) {
                map.put("f_sex", "男");
            }
            map.put("tag_year", StringUtils.isNotEmpty(privateTO.getAge()) ? privateTO.getAge() : "");
            map.put("tag_job", StringUtils.isNotEmpty(privateTO.getCareer()) ? privateTO.getCareer() : "");
            map.put("arrive_store_distance", StringUtils.isNotEmpty(privateTO.getDistance()) ? privateTO.getDistance() : "");

            ConsumerStyleQO consumerStyleQO = new ConsumerStyleQO();
            consumerStyleQO.setConsumerId(f_user_id);
            consumerStyleQO.setType(1);
            consumerStyleQO.setIsDelete(YesNoEnum.NO);
            List<ConsumerStyleTO> styleList = consumerStyleService.selectConsumerStyleList(consumerStyleQO);
            if (styleList != null && styleList.size() > 0) {
                if (styleList.size() == 1) {
                    map.put("tag_feel_style", StringUtils.isNotEmpty(styleList.get(0).getStyle()) ? styleList.get(0).getStyle() : "");
                } else {
                    map.put("tag_feel_style", StringUtils.isNotEmpty(styleList.get(styleList.size() - 1).getStyle()) ? styleList.get(styleList.size() - 1).getStyle() + "等" : "");
                }
            }
        }

        return map;
    }


    /**
     * 修改用户年龄标签
     *
     * @param f_user_id
     * @param time
     * @param token
     * @param selected_tag
     * @param mobile_type
     * @throws Throwable
     */
    public void updateConsumerPrivateAge(long f_user_id, String time, String token, int selected_tag, String mobile_type) throws Throwable {
        ConsumerTO consumerTO = consumerService.selectByPrimary(f_user_id);
        if (null == consumerTO || consumerTO.getId() <= 0) {
            throw new DataException(DataException.Type.DEFAULT, "用户不存在");
        }
        ConsumerPrivateTO privateTO = consumerPrivateService.selectByPrimary(consumerTO.getId());
        consumerPrivateService.update(privateTO.setAgeId(selected_tag).setAge(AgeEnums.getNameById(selected_tag)));
    }

    /**
     * 修改用户性别
     *
     * @param f_user_id
     * @param time
     * @param token
     * @param f_sex       1男 2女
     * @param mobile_type
     * @throws Throwable
     */
    public void updateConsumerPrivateSex(long f_user_id, String time, String token, int f_sex, String mobile_type) throws Throwable {
        ConsumerTO consumerTO = consumerService.selectByPrimary(f_user_id);
        if (null == consumerTO || consumerTO.getId() <= 0) {
            throw new DataException(DataException.Type.DEFAULT, "用户不存在");
        }
        ConsumerPrivateTO privateTO = consumerPrivateService.selectByPrimary(consumerTO.getId());
        if (1 == f_sex) {
            privateTO.setSex(SexEnum.MALE);
            consumerPrivateService.update(privateTO);
        } else if (2 == f_sex) {
            privateTO.setSex(SexEnum.FEMALE);
            consumerPrivateService.update(privateTO);
        }
    }

    /**
     * 修改用户职业
     *
     * @param f_user_id
     * @param time
     * @param token
     * @param f_frequency
     * @param mobile_type
     * @throws Throwable
     */
    public void updateConsumerPrivateCareer(long f_user_id, String time, String token, int f_professional_attributes, String mobile_type) throws Throwable {
        ConsumerTO consumerTO = consumerService.selectByPrimary(f_user_id);
        if (null == consumerTO || consumerTO.getId() <= 0) {
            throw new DataException(DataException.Type.DEFAULT, "用户不存在");
        }
        ConsumerPrivateTO privateTO = consumerPrivateService.selectByPrimary(consumerTO.getId());
        consumerPrivateService.update(privateTO.setCareerId(f_professional_attributes).setCareer(CareerEnums.getNameById(f_professional_attributes)));
    }

    /**
     * 查询用户风格定位  pantong
     *
     * @param consumerStyleQO
     * @return
     * @throws Throwable
     */
    public List<ConsumerStyleTO> getConsumerStylsList(ConsumerStyleQO consumerStyleQO) throws Throwable {
        return consumerStyleService.selectConsumerStyleList(consumerStyleQO);
    }

    /**
     * 修改用户定位风格 pantong
     *
     * @param f_user_id
     * @param time
     * @param token
     * @param choose_style_list_ids
     * @param mobile_type
     * @throws Throwable
     */
    @Transactional
    public void updateConsumerStyle(long f_user_id, String time, String token, String choose_style_list_ids, String mobile_type) throws Throwable {
        ConsumerTO consumerTO = consumerService.selectByPrimary(f_user_id);
        if (null == consumerTO || consumerTO.getId() <= 0) {
            throw new DataException(DataException.Type.DEFAULT, "用户不存在");
        }

        //将该用户之前的风格设置删除
        ConsumerStyleQO consumerStyleQO = new ConsumerStyleQO();
        consumerStyleQO.setConsumerId(f_user_id);
        List<ConsumerStyleTO> toDeleteList = consumerStyleService.selectConsumerStyleList(consumerStyleQO);
        if (toDeleteList != null && toDeleteList.size() > 0) {
//            toDeleteList.stream().map(a->a.setIsDelete(YesNoEnum.YES)).collect(Collectors.toList());
            for (int i = 0; i < toDeleteList.size(); i++) {
                ConsumerStyleTO t = toDeleteList.get(i);
                t.setIsDelete(YesNoEnum.YES);
                consumerStyleService.updateConsumerStyle(t);
            }
        }

        //保存修改后的
        if (StringUtils.isNotEmpty(choose_style_list_ids)) {
            String[] ids = choose_style_list_ids.split(",");
            if (ids != null && ids.length > 0) {
                for (int i = 0; i < ids.length; i++) {
                    if (StringUtils.isNotEmpty(ids[i])) {
                        ConsumerStyleTO t = new ConsumerStyleTO();
                        t.setType(1);
                        t.setStyleId(ids[i]);
                        t.setStyle(HairStyleEnums.getNameById(ids[i]));
                        t.setConsumerId(f_user_id);
                        t.setIsDelete(YesNoEnum.NO);
                        consumerStyleService.addConsumerStyle(t);
                    }
                }
            }
        }
    }


    /**
     * 查询分页消费者列表
     *
     * @return : com.baomidou.mybatisplus.extension.plugins.pagination.Page<com.xingkeduo.pojo.query.ConsumerOrderQO>
     * @author : gaozifeng
     * @date : 2019/2/21 13:54
     */
    public List<ConsumerTO> selectConsumerAllByPage(ConsumerQO consumerQO, ConsumerStatisticsQO stsQO,
                                                    ConsumerPrivateQO privateQO, Page<ConsumerTO> page) throws Throwable {
        long startTime = System.currentTimeMillis();
        //根据昵称、手机号查询id集合
        List<Long> nickNameIds = null;
        ConsumerQO nickNameConsumerQO;
        //根据昵称查  支持加密和非加密匹配

        if (StringUtils.isNotEmpty(consumerQO.getCondition()) && !RegularUtil.isPositiveInteger(consumerQO.getCondition())) {
            nickNameConsumerQO = new ConsumerQO();
            nickNameConsumerQO.setName(consumerQO.getCondition());
            nickNameConsumerQO.setCondition(consumerQO.getCondition()).setIsDelete(YesNoEnum.NO);
            nickNameIds = consumerService.selectConsumerListForid(nickNameConsumerQO);
        }
        List<Long> phoneIds = null;
        ConsumerPrivateQO phoneConsumerPrivateQO;
        if (StringUtils.isNotEmpty(privateQO.getPhone())) {//根据手机号查
            phoneConsumerPrivateQO = new ConsumerPrivateQO();
            phoneConsumerPrivateQO.setIsDelete(YesNoEnum.NO).setPhone(privateQO.getPhone());
            phoneIds = consumerPrivateService.selectUserPrivateForId(phoneConsumerPrivateQO);
        }

        if (StringUtils.isNotEmpty(consumerQO.getCondition()) && RegularUtil.isPositiveInteger(consumerQO.getCondition()) && !RegularUtil.isSelfPhone(consumerQO.getCondition())) {
            consumerQO.setId(Long.parseLong(consumerQO.getCondition()));
        }

        List<Long> conditionIds = new ArrayList<Long>();//根据昵称、手机号查询id集合
        if (StringUtils.isNotEmpty(consumerQO.getCondition()) || StringUtils.isNotEmpty(privateQO.getPhone())) {
            if ((nickNameIds == null || nickNameIds.size() <= 0) && (phoneIds == null || phoneIds.size() <= 0) && consumerQO.getId() == 0) {
                return Collections.emptyList();
            }
            if (nickNameIds != null && nickNameIds.size() > 0) {
                conditionIds.addAll(nickNameIds);
            }
            if (phoneIds != null && phoneIds.size() > 0) {
                conditionIds.addAll(phoneIds);
            }
            if (CommonUtil.isEmpty(conditionIds) && consumerQO.getId() == 0) {
                return Collections.emptyList();
            }
        }
        //根据年龄\性别查询符合条件的id集合 排除phone
        List<Long> privateIds = null;
        privateQO.setPhone(null);//手机置空
        if (!privateQO.isEmpty()) {
            privateIds = consumerPrivateService.selectUserPrivateForId(privateQO.setIsDelete(YesNoEnum.NO));
            if (CommonUtil.isEmpty(privateIds))
                return Collections.emptyList();
        }
        //根据服务次数查询符合条件的id集合
        List<Long> serviceNumIds = null;
        if (!stsQO.isEmpty()) {
            stsQO.setIsDelete(YesNoEnum.NO);
            serviceNumIds = consumerStatisticsService.selectUserPrivateForId(stsQO);
            if (CommonUtil.isEmpty(serviceNumIds))
                return Collections.emptyList();
        }
        //并集获取符合条件的数据并分页查询
        List<Long> ids = new ArrayList<>();//合并后的ids交集
        if (conditionIds != null) {
            ids.addAll(conditionIds);
        }
        if (privateIds != null) {
            if (ids.size() > 0) {
                ids.retainAll(privateIds);
                if (ids.size() <= 0) {
                    return Collections.emptyList();
                }
            } else {
                ids.addAll(privateIds);
            }
        }
        if (serviceNumIds != null) {
            if (ids.size() > 0) {
                ids.retainAll(serviceNumIds);
                if (ids.size() <= 0) {
                    return Collections.emptyList();
                }
            } else {
                ids.addAll(serviceNumIds);
            }
        }

        //排除condition 根据微信粉丝  用户类型 和ids并集 查询符合条件的数据集合
        List<ConsumerTO> consumerList = new ArrayList<ConsumerTO>();
        consumerQO.setCondition(null);
        consumerQO.setIds(ids);

        int count = consumerService.count(consumerQO);
        if (count == 0) {
            return consumerList;
        }
        page.init(count);
        consumerQO.setRecordStart(page.getRecordStart()).setRecordEnd(page.getRecordEnd());
        consumerList = consumerService.selectConsumerList(consumerQO);


        if (consumerList != null && consumerList.size() > 0) {
            List<Long> userListId = consumerList.stream().map(a -> a.getId()).collect(Collectors.toList());

            ConsumerFileQO fileQO = new ConsumerFileQO();
            fileQO.setConsumerIds(userListId).setIsDelete(YesNoEnum.NO);
            List<ConsumerFileTO> userFileList = consumerFileService.selectConsumerFileList(fileQO);
            Map<Long, ConsumerFileTO> fileMap = userFileList.stream().collect(Collectors.toMap(ConsumerFileTO::getConsumerId, a -> a, (k1, k2) -> k1));

            List<ConsumerStatisticsTO> statisticsList = consumerStatisticsService.selectConsumerForList(new ConsumerStatisticsQO().setIds(userListId).setIsDelete(YesNoEnum.NO));
            Map<Long, ConsumerStatisticsTO> statisticsMap = statisticsList.stream().collect(Collectors.toMap(ConsumerStatisticsTO::getId, a -> a, (k1, k2) -> k1));

            List<ConsumerPrivateTO> privateList = consumerPrivateService.selectUserPrivateList(new ConsumerPrivateQO().setIds(userListId).setIsDelete(YesNoEnum.NO));
            Map<Long, ConsumerPrivateTO> privateMap = privateList.stream().collect(Collectors.toMap(ConsumerPrivateTO::getId, a -> a, (k1, k2) -> k1));

            for (int i = 0; i < consumerList.size(); i++) {
                long consumerId = consumerList.get(i).getId();
                ConsumerFileTO fileTO = fileMap.get(consumerId);
                ConsumerStatisticsTO consumerStatisticsTO = statisticsMap.get(consumerId);
                ConsumerPrivateTO privateTO = privateMap.get(consumerId);
                if (null != fileTO) {
                    consumerList.get(i).setFileTO(fileTO);
                }
                if (null != consumerStatisticsTO) {
                    consumerList.get(i).setTo(consumerStatisticsTO);
                }
                if (null != privateTO) {
                    consumerList.get(i).setPrivateTO(privateTO);
                }
            }
        }
        page.setDtoList(consumerList);
        long endTime = System.currentTimeMillis();
        log.info("耗时[{}]", endTime - startTime);
        return consumerList;
    }

    /**
     * 返回id，name，phone  查询条件 给远程调的
     *
     * @param consumerQO:
     * @param queryCondition:
     * @return : com.xingkeduo.pojo.table.ConsumerTO
     * @author : gaozifeng
     * @date : 2019/4/29 16:20
     */
    public List<ConsumerDTO> getConsumerByCondition(ConsumerQO consumerQO, ConsumerPrivateQO queryCondition) throws Throwable {
        log.info("用户查询条件 getConsumerByCondition consumerQO ," + JSON.toJSONString(consumerQO));
        log.info("用户查询条件 getConsumerByCondition queryCondition ," + JSON.toJSONString(queryCondition));

        if (0L == consumerQO.getId() && StringUtils.isEmpty(queryCondition.getPhone()) && StringUtils.isEmpty(consumerQO.getCondition())) {
            throw new DataException(DataException.Type.DEFAULT, "条件不能为空");
        }
        List<ConsumerTO> consumerList = null;
        List<ConsumerPrivateTO> privateList = null;
        List<Long> consumerIds = null;
        if (0L != consumerQO.getId() || StringUtils.isNotEmpty(consumerQO.getCondition())) {
            consumerList = consumerService.selectConsumerList(consumerQO);
            if (null == consumerList || consumerList.size() <= 0) {
                throw new DataException(DataException.Type.DEFAULT, "没有查询到用户信息");
            }
            consumerIds = consumerList.stream().map(a -> a.getId()).collect(Collectors.toList());
            privateList = consumerPrivateService.selectUserPrivateList(new ConsumerPrivateQO().setIds(consumerIds));
        } else {
            //consumer没有查询的，要查 手机号
            privateList = consumerPrivateService.selectUserPrivateList(queryCondition);
            if (null == privateList || privateList.size() <= 0) {
                throw new DataException(DataException.Type.DEFAULT, "没有查询到用户信息");
            }
            consumerIds = privateList.stream().map(a -> a.getId()).collect(Collectors.toList());
            consumerList = consumerService.selectConsumerList(new ConsumerQO().setIds(consumerIds));
        }
        if (null == consumerList && consumerList.size() <= 0 && null == privateList && privateList.size() <= 0) {
            throw new DataException(DataException.Type.DEFAULT, "没有查询到用户信息");
        }
        List<ConsumerDTO> collect = new ArrayList<>(10);
        ConsumerDTO dto;
        for (ConsumerTO co : consumerList) {
            dto = new ConsumerDTO();
            dto.setId(co.getId());
            dto.setName(co.getName() != null ? Base64Utils.decoderParam(co.getName()) : "");
            collect.add(dto);
        }
        Map<Long, ConsumerPrivateTO> map = privateList.stream().collect(Collectors.toMap(ConsumerPrivateTO::getId, a -> a, (k1, k2) -> k1));
        List<ConsumerDTO> returnList = collect.stream().peek(c -> {
            ConsumerPrivateTO privateTO = map.get(c.getId());
            if (c.getId() == privateTO.getId()) {
                c.setPhone(privateTO.getPhone());
            }
        }).collect(Collectors.toList());
        //TODO 李鑫出现入参和返回不同的情况
        log.info("返回的参数集合getConsumerByCondition[{}]",JSON.toJSONString(returnList));
        return returnList;
    }

    /**
     * 返回id集合   查询用户id,phone,name
     *
     * @param consumerQO:
     * @param queryCondition:
     * @return : java.util.List<java.lang.Long>
     * @author : gaozifeng
     * @date : 2019/7/5 11:57
     */
    public Set<Long> getConsumerIdByCondition(ConsumerQO consumerQO, ConsumerPrivateQO queryCondition) throws Throwable {
        if (0L == consumerQO.getId() && StringUtils.isEmpty(queryCondition.getPhone()) && StringUtils.isEmpty(consumerQO.getNameOrPhone())) {
            throw new DataException(DataException.Type.DEFAULT, "条件不能为空");
        }
        Set<Long> set = null;
        List<Long> userListIds = null;
        if (0L != consumerQO.getId()) {
            userListIds = consumerService.selectConsumerListForid(consumerQO);
            if (userListIds.get(0) > 0L) {
                ConsumerPrivateTO privateTO = consumerPrivateService.selectByPrimary(userListIds.get(0));
                if (null != privateTO) {
                    if (null != privateTO.getPhone()) {
                        List<Long> list = consumerPrivateService.selectUserPrivateForId(new ConsumerPrivateQO().setPhone(privateTO.getPhone()).setIsDelete(YesNoEnum.NO));
                        userListIds.addAll(list);
                    }
                }
            }
            set = new HashSet<>(userListIds);
            return set;
        }
        if (StringUtils.isNotBlank(consumerQO.getNameOrPhone())) {
            userListIds = consumerService.selectConsumerListForid(consumerQO.setIsDelete(YesNoEnum.NO));
        }
        if (StringUtils.isNotBlank(queryCondition.getPhone())) {
            if (userListIds == null) {
                userListIds = consumerPrivateService.selectUserPrivateForId(queryCondition.setIsDelete(YesNoEnum.NO));
            } else {
                List<Long> userPhoneIds = consumerPrivateService.selectUserPrivateForId(queryCondition.setIsDelete(YesNoEnum.NO));
                userListIds.addAll(userPhoneIds);
            }
        }
        if (null != userListIds && userListIds.size() > 0) {
            set = new HashSet<>(userListIds);
            return set;
        }
        return new HashSet<>();
    }

    public List<ConsumerDTO> selectUserListForIds(String ids) throws Throwable {
        log.info("查询用户集合,参数ids[{}]", ids);
        if (StringUtils.isEmpty(ids)) {
            throw new DataException(DataException.Type.NULL, "用户集合");
        }
        String[] split = ids.split(",");
        List<String> list = Arrays.asList(split);
        List<ConsumerDTO> returnList;
        if (null != list || list.size() > 0) {
            List<Long> collect = list.stream().map(a -> Long.parseLong(a)).collect(Collectors.toList());
            List<ConsumerTO> consumerList = consumerService.selectConsumerList(new ConsumerQO().setIds(collect));
            returnList = new LinkedList<>();
            List<ConsumerPrivateTO> privateList = consumerPrivateService.selectUserPrivateList(new ConsumerPrivateQO().setIds(collect));
            Map<Long, ConsumerPrivateTO> privateTOMap = privateList.stream().collect(Collectors.toMap(ConsumerPrivateTO::getId, a -> a, (k1, k2) -> k1));
            for (ConsumerTO consumerTO : consumerList) {
                ConsumerDTO dto = new ConsumerDTO();
                dto.setId(consumerTO.getId()).setName(Base64Utils.decoderParam(consumerTO.getName()));
                ConsumerPrivateTO privateTO = privateTOMap.get(consumerTO.getId());
                if (null != privateTO && null != privateTO.getPhone()) {
                    dto.setPhone(privateTO.getPhone());
                } else {
                    dto.setPhone("");
                }
                returnList.add(dto);
            }
        } else {
            throw new DataException(DataException.Type.NULL, "用户信息");
        }
        return returnList;
    }


    /**
     * 新增小程序用户新增用户
     *
     * @param wxMaUserInfo:
     * @return : void
     * @author : gaozifeng
     * @date : 2019/5/8 16:21
     */
    @Transactional
    public String insertConsumerInfo(WxMaUserInfo wxMaUserInfo) throws Throwable {
//        wxMaUserInfo
//                .setGender("2")
//                .setNickName("小机灵鬼")
//                .setCity("静安")
//                .setLanguage("zh_CN")
//                .setOpenId("oEEnq0OEEtKODFfXjgrhlSVvGKUU")
//                .setAvatarUrl("https://wx.qlogo.cn/mmopen/vi_32/PF1G3zBhiaWhViaMBGZ9bkLQZjqklicktUPaPnt7yQMSJFBqVPtHxBgYCm7WWs8zHhwqRzz0ibY88KTkrdNmHLZleQ/132")
//                .setUnionId("oRAZ-xK_iyHKfPBonBfNTREVhBtE");
        log.info("小程序授权新增用户接口------------------" + JSON.toJSONString(wxMaUserInfo.toString()));
        if (null == wxMaUserInfo.getUnionId() || ("").equals(wxMaUserInfo.getUnionId())) {
            throw new DataException(DataException.Type.DEFAULT, "获取用户信息失败.");
        }
        List<ConsumerTO> consumerList = consumerService.selectConsumerList(new ConsumerQO().setLogin(wxMaUserInfo.getUnionId()));
        if (null == consumerList || consumerList.size() <= 0) {
            ConsumerTO consumerTO = new ConsumerTO();
            consumerTO.setLogin(wxMaUserInfo.getUnionId())
                    .setType(UserTypeEnums.WX.getType())
                    .setIsDelete(YesNoEnum.NO);

            if (null != wxMaUserInfo.getNickName()) {
                consumerTO.setName(Base64Utils.encodeParam(wxMaUserInfo.getNickName()));
            }
            consumerService.insertConsumer(consumerTO);
            log.info("新增用户表记录:" + consumerTO.toString());
            log.info("新增用户表记录id--------------:" + consumerTO.getId());
            ConsumerPrivateTO privateTO = new ConsumerPrivateTO();
            privateTO.setCityId(wxMaUserInfo.getCity())
                    .setSex(("1").equals(wxMaUserInfo.getGender()) ? SexEnum.MALE : SexEnum.FEMALE).setMinaOpenId(wxMaUserInfo.getOpenId())
                    .setIsDelete(YesNoEnum.NO).setId(consumerTO.getId()).setCountry(wxMaUserInfo.getCountry())
                    .setProvince(wxMaUserInfo.getProvince()).setLanguage(wxMaUserInfo.getLanguage());

            consumerPrivateService.insert(privateTO);
            log.info("新增用户表记录:" + privateTO.toString());
            ConsumerFileTO fileTO = new ConsumerFileTO();

            fileTO.setType(UserTypeEnums.WX.getType()).setPath(wxMaUserInfo.getAvatarUrl()).setIsDelete(YesNoEnum.NO).setConsumerId(consumerTO.getId());
            consumerFileService.insertConsumer(fileTO);
            log.info("新增用户表记录:" + fileTO.toString());

            return String.valueOf(consumerTO.getId());
        } else {
            ConsumerTO consumerTO = consumerList.stream().findFirst().orElse(null);
            log.info("小程序授权 已经存在此账号");
            ConsumerPrivateTO privateTO = consumerPrivateService.selectByPrimary(consumerTO.getId());
            log.info("查看本账号是否已经拥有小程序openid");
            ConsumerFileQO fileQO = new ConsumerFileQO();
            fileQO.setConsumerId(consumerTO.getId());
            fileQO.setType(UserTypeEnums.WX.getType());
            fileQO.setIsDelete(YesNoEnum.NO);
            List<ConsumerFileTO> consumerFileTOS = consumerFileService.selectConsumerFileList(fileQO);
            if (null == privateTO) {
                log.info("小程序用户[{}]授权，private 表 数据丢失,重新添加", consumerTO.getId());
                privateTO = new ConsumerPrivateTO();
                privateTO.setId(consumerTO.getId()).setCityId(wxMaUserInfo.getCity())
                        .setSex(("1").equals(wxMaUserInfo.getGender()) ? SexEnum.MALE : SexEnum.FEMALE).setMinaOpenId(wxMaUserInfo.getOpenId())
                        .setIsDelete(YesNoEnum.NO).setId(consumerTO.getId()).setCountry(wxMaUserInfo.getCountry())
                        .setProvince(wxMaUserInfo.getProvince()).setLanguage(wxMaUserInfo.getLanguage());
                consumerPrivateService.insert(privateTO);
                if (null == privateTO.getMinaOpenId()) {
                    log.info("用户[{}]没有openid,之前是公众号先登录的,要设置小程序openid", wxMaUserInfo.getOpenId());
                    privateTO.setMinaOpenId(wxMaUserInfo.getOpenId());
                    consumerPrivateService.update(privateTO);
                }
            } else {
                if (null == consumerFileTOS || consumerFileTOS.size() <= 0) {
                    log.info("小程序授权 用户[{}]没有头像,填充头像信息", consumerTO.getId());
                    ConsumerFileTO fileTO = new ConsumerFileTO();
                    fileTO.setType(UserTypeEnums.WX.getType()).setPath(wxMaUserInfo.getAvatarUrl()).setIsDelete(YesNoEnum.NO).setConsumerId(consumerTO.getId());
                    consumerFileService.insertConsumer(fileTO);
                }
                if (StringUtils.isBlank(privateTO.getMinaOpenId())) {
                    log.info("小程序授权 用户[{}],没有openid ,要设置小程序openid[{}]", consumerTO.getId(), wxMaUserInfo.getOpenId());
                    privateTO.setMinaOpenId(wxMaUserInfo.getOpenId());
                    consumerPrivateService.update(privateTO);
                }
            }
            return String.valueOf(consumerTO.getId());
        }

    }

    /**
     * 消费者详情接口
     *
     * @param consumerQO:
     * @return : com.xingkeduo.pojo.table.ConsumerTO
     * @author : gaozifeng
     * @date : 2019/2/27 18:55
     */
    public ConsumerTO userDetail(ConsumerQO consumerQO) throws Throwable {
        ConsumerTO user = consumerService.selectByPrimary(consumerQO.getId());
        if (null != user) {

            List<Long> manyConsumerIds = getManyConsumerIds(user.getId());
            List<ConsumerStatisticsTO> statisticsList = consumerStatisticsService
                    .selectConsumerForList(new ConsumerStatisticsQO().setIds(manyConsumerIds).setIsDelete(YesNoEnum.NO));
            ConsumerStatisticsTO consumerStatisticsTO = null;
            if (null != statisticsList) {
                if (statisticsList.size() == 2) {
                    consumerStatisticsTO = mergeConsumerStatisticsTOS(statisticsList);
                } else {
                    consumerStatisticsTO = consumerStatisticsService.selectByPrimary(consumerQO.getId());
                }
            }
            ConsumerPrivateTO privateTO = consumerPrivateService.selectByPrimary(consumerQO.getId());
            user.setTo(consumerStatisticsTO);
            user.setPrivateTO(privateTO);

            //头像信息
            ConsumerFileQO fileQO = new ConsumerFileQO();
            fileQO.setConsumerId(consumerQO.getId());
            fileQO.setIsDelete(YesNoEnum.NO);
            List<ConsumerFileTO> fileTOList = consumerFileService.selectConsumerFileList(fileQO);
            if (fileTOList != null && fileTOList.size() > 0) {
                user.setFileTO(fileTOList.get(0));
            }
            //style
            ConsumerStyleQO consumerStyleQO = new ConsumerStyleQO();
            consumerStyleQO.setConsumerId(consumerQO.getId());
            consumerStyleQO.setType(1);
            consumerStyleQO.setIsDelete(YesNoEnum.NO);
            List<ConsumerStyleTO> styleList = consumerStyleService.selectConsumerStyleList(consumerStyleQO);
            user.setStyleList(styleList);

            return user;
        }
        return null;
    }

    private ConsumerStatisticsTO mergeConsumerStatisticsTOS(List<ConsumerStatisticsTO> statisticsList) {
        ConsumerStatisticsTO consumerStatisticsTO = new ConsumerStatisticsTO();
        for (ConsumerStatisticsTO statisticsTO : statisticsList) {
            if (consumerStatisticsTO.getId() == 0L) {
                consumerStatisticsTO = statisticsTO;
            } else {
                consumerStatisticsTO.setPayCount(Optional.ofNullable(statisticsTO.getPayCount()).orElse(0) + Optional.ofNullable(consumerStatisticsTO.getPayCount()).orElse(0));
                if (null != consumerStatisticsTO.getLastTime() && null != statisticsTO.getLastTime()) {
                    consumerStatisticsTO.setLastTime(consumerStatisticsTO.getLastTime().getTime() > statisticsTO.getLastTime().getTime() ? consumerStatisticsTO.getLastTime() : statisticsTO.getLastTime());
                } else if (null != statisticsTO.getLastTime() && null == consumerStatisticsTO.getLastTime()) {
                    consumerStatisticsTO.setLastTime(statisticsTO.getLastTime());
                } else {
                    consumerStatisticsTO.setLastTime(consumerStatisticsTO.getLastTime());
                }
                consumerStatisticsTO.setServiceTotal(Optional.ofNullable(statisticsTO.getServiceTotal()).orElse(0) + Optional.ofNullable(consumerStatisticsTO.getServiceTotal()).orElse(0));
                consumerStatisticsTO.setRefundMoney(Optional.ofNullable(statisticsTO.getRefundMoney()).orElse(BigDecimal.ZERO).add(Optional.ofNullable(consumerStatisticsTO.getRefundMoney()).orElse(BigDecimal.ZERO)));
                consumerStatisticsTO.setServiceMoney(Optional.ofNullable(statisticsTO.getServiceMoney()).orElse(BigDecimal.ZERO).add(Optional.ofNullable(consumerStatisticsTO.getServiceMoney()).orElse(BigDecimal.ZERO)));
            }
        }
        return consumerStatisticsTO;
    }


    /**
     * 查询用户是否新用户
     *
     * @param consumerStatisticsQO:
     * @return : java.lang.Boolean
     * @author : gaozifeng
     * @date : 2019/7/15 15:09
     */
    public Boolean checkNewComer(ConsumerStatisticsQO consumerStatisticsQO) throws Throwable {
        checkConsumerStatus(consumerStatisticsQO.getId());

        List<Long> manyConsumerIds = getManyConsumerIds(consumerStatisticsQO.getId());

        Boolean flag = checkNewConsumers(manyConsumerIds);
        log.info("发券处判断是否新用户id[{}],flag[{}]", consumerStatisticsQO.getId(), flag);
        return flag;
    }

    /**
     * 检查多账号 是否新用户 当某一端领取之后 另一端 也不让领
     *
     * @param consumerIds:
     * @return : java.lang.Boolean
     * @author : gaozifeng
     * @date : 2019/7/22 10:56
     */
    private Boolean checkNewConsumers(List<Long> consumerIds) throws Throwable {
        List<ConsumerStatisticsTO> statistics = consumerStatisticsService
                .selectConsumerForList(new ConsumerStatisticsQO().setIds(consumerIds).setIsDelete(YesNoEnum.NO));

        Boolean flag = true;
        if (null != statistics && statistics.size() > 0) {
            long count = statistics.stream().filter(a -> null != a.getFirstPayTime()).count();
            if (count > 0) {
                flag = false;
            }
        }

        return flag;
    }

    /**
     * 获取账户合并
     *
     * @param consumerId:
     * @return : java.util.List<java.lang.Long>
     * @author : gaozifeng
     * @date : 2019/7/22 10:45
     */
    private List<Long> getManyConsumerIds(Long consumerId) throws Throwable {
        ConsumerPrivateTO consumerPrivate = getConsumerPrivateById(consumerId);
        if (null != consumerPrivate) {
            if (null != consumerPrivate.getPhone()) {
                List<ConsumerRelateTO> relateList = relateService
                        .selectConsumerRelateList(new ConsumerRelateQO().setPhone(consumerPrivate.getPhone()).setIsDelete(YesNoEnum.NO));
                return relateList.stream().map(BaseTable::getId).collect(Collectors.toList());
            }
        }
        return Arrays.asList(consumerId);
    }

    /**
     * 返回是新用户的集合
     *
     * @param consumerStatisticsDTOS:
     * @return : com.xingkeduo.pojo.table.ConsumerStatisticsTO
     * @author : gaozifeng
     * @date : 2019/7/17 15:03
     */
    public List<ConsumerStatisticsDTO> newConsumerList(List<ConsumerStatisticsDTO> consumerStatisticsDTOS) throws Throwable {
        if (null == consumerStatisticsDTOS || consumerStatisticsDTOS.size() == 0) {
            throw new InputParamException(InputParamException.Type.EMPTY, "参数");
        }
        List<Long> consumerIds = consumerStatisticsDTOS.stream().map(ConsumerStatisticsDTO::getId).collect(Collectors.toList());

        List<ConsumerStatisticsTO> statisticsList = consumerStatisticsService.selectConsumerForList(new ConsumerStatisticsQO().setIds(consumerIds));
        if (null == statisticsList || statisticsList.size() == 0) {
            log.info("获取消费者统计表userId[{}]不存在", JSON.toJSONString(consumerIds));
            return null;
        }
        List<ConsumerStatisticsDTO> returnList = new LinkedList<>();

        Map<Long, ConsumerStatisticsDTO> requestMap = consumerStatisticsDTOS.stream().collect(Collectors.toMap(ConsumerStatisticsDTO::getId, a -> a, (k1, k2) -> k1));

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (ConsumerStatisticsTO consumerStatisticsTO : statisticsList) {
            ConsumerStatisticsDTO consumerStatisticsDTO = new ConsumerStatisticsDTO();
            if (null != consumerStatisticsTO.getFirstPayTime()) {
                ConsumerStatisticsDTO reqeustDTO = requestMap.get(consumerStatisticsTO.getId());
                if (null != reqeustDTO && null != reqeustDTO.getPayTime()) {
                    //比较时间
                    long dataTime = consumerStatisticsTO.getFirstPayTime().getTime();
                    Long requestTime = sdf.parse(reqeustDTO.getPayTime()).getTime();

                    if (dataTime == requestTime && 0L != dataTime) {
                        consumerStatisticsDTO.setId(consumerStatisticsTO.getId());
                        consumerStatisticsDTO.setPayTime(reqeustDTO.getPayTime());
                        returnList.add(consumerStatisticsDTO);
                    }
                }
            }
        }
        return returnList;
    }


    /**
     * 验证用户异常状态
     *
     * @param consumerId:
     * @return : void
     * @author : gaozifeng
     * @date : 2019/7/17 15:02
     */
    private void checkConsumerStatus(Long consumerId) throws Throwable {
        ConsumerTO consumerTO = consumerService.selectByPrimary(consumerId);
        if (null == consumerTO) {
            throw new BusinessException(BusinessException.Type.DEFAULT, "消费者不存在");
        }
        if (YesNoEnum.YES == consumerTO.getIsDelete() || consumerTO.getfStatus() == ConsumerStatusEnums.BLACK_LIST) {
            log.info("消费者信息问题数据 consumer[{}]", JSON.toJSONString(consumerTO));
            throw new BusinessException(BusinessException.Type.DEFAULT, "消费者数据异常");
        }
    }

    /**
     * 新增消费者统计表
     *
     * @param consumerStatisticsDTO:
     * @return : void
     * @author : gaozifeng
     * @date : 2019/3/14 17:37
     */
    @Transactional
    public void insertConsumerStatistics(ConsumerStatisticsDTO consumerStatisticsDTO) throws Throwable {
        log.info("消费者统计服务次数." + JSON.toJSONString(consumerStatisticsDTO));
        ConsumerTO consumerTO = consumerService.selectByPrimary(consumerStatisticsDTO.getId());
        if (null == consumerTO) {
            throw new BusinessException(BusinessException.Type.DEFAULT, "消费者不存在");
        }
        ConsumerStatisticsTO statisticsTO = consumerStatisticsService.selectByPrimary(consumerStatisticsDTO.getId());
        /*
         * 其实数据没有的话 只判断支付成功就可以了，怕老数据那有问题.
         */
        Boolean flag;
        if (null == statisticsTO) {
            flag = insertConsumerServiceTable(consumerStatisticsDTO);
        } else {
            flag = updateConsumerServiceTable(statisticsTO, consumerStatisticsDTO);
        }
        log.info("insertConsumerStatistics flag【{}】",flag);
        if (flag) {
            log.info("老用户发券");
            //老用户发券
            ShareReceiveTO newConsumerReceiveInfo = getNewConsumerReceiveInfo(consumerStatisticsDTO.getId(), consumerStatisticsDTO.getCouponId());
            if (null != newConsumerReceiveInfo) {
                sendConsumerCoupon(newConsumerReceiveInfo, consumerStatisticsDTO.getOrderNo());
            }
            ConsumerPrivateTO privateTO = consumerPrivateService.selectByPrimary(newConsumerReceiveInfo.getConsumerId());
            if (null != privateTO) {
                if (null != privateTO.getGzhOpenId()) {
                    StringBuilder sb = new StringBuilder();
                    sb.append(INVITE_PRE);
                    sb.append(Base64Utils.decoderParam(consumerTO.getName()));
                    sb.append(INVITE_SUF);
                    MsgTempDTO msgTempDTO = new MsgTempDTO();
                    msgTempDTO.setOpenId(privateTO.getGzhOpenId());
                    msgTempDTO.setContent(sb.toString());
                    eventHandleService.eventHandle(SendingTypeEnum.MSG_TEMP, msgTempDTO);
                }
            }
        }
    }


    private Boolean insertConsumerServiceTable(ConsumerStatisticsDTO consumerStatisticsDTO) throws Throwable {
        //新增一条记录
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ConsumerStatisticsTO statisticsTO = new ConsumerStatisticsTO();
        statisticsTO.setId(consumerStatisticsDTO.getId())
                .setCreatedBy(consumerStatisticsDTO.getId())
                .setCreatedTime(new Date())
                .setIsDelete(YesNoEnum.NO);
        Boolean flag = false;
        switch (consumerStatisticsDTO.getConsumNotice()) {
            case PAY_SUCCESS:
                //支付成功
                statisticsTO.setPayCount(addInt).setFirstPayTime(sdf.parse(consumerStatisticsDTO.getPayTime()));
                break;
            case REFUND_SUCCESS:
                //退款
                statisticsTO.setRefundMoney(consumerStatisticsDTO.getRefundMoney());
                break;
            case CONSUME_SUCCESS:
                //消费成功
                statisticsTO.setServiceTotal(addInt)
                        .setServiceMoney(consumerStatisticsDTO.getServiceMoney())
                        .setLastTime(sdf.parse(consumerStatisticsDTO.getLastTime()))
                        .setRefundMoney(new BigDecimal(0));
                break;
            case CONSUME_START:
                //开始服务 发券通知
                if (null != consumerStatisticsDTO.getCouponId()) {
                    flag = consumerReceiveCoupon(consumerStatisticsDTO.getCouponId(), consumerStatisticsDTO.getId());
                }
                break;
            default:
                throw new InputParamException(InputParamException.Type.INVALID, "传输类型不存在");
        }
        consumerStatisticsService.insert(statisticsTO);
        return flag;
    }

    /**
     * 修改用户服务表
     *
     * @param statisticsTO:
     * @param consumerStatisticsDTO:
     * @return : java.lang.Boolean
     * @author : gaozifeng
     * @date : 2019/7/13 11:16
     */
    private Boolean updateConsumerServiceTable(ConsumerStatisticsTO statisticsTO, ConsumerStatisticsDTO
            consumerStatisticsDTO) throws Throwable {
        log.info("修改 用户服务记录,[{}]", JSON.toJSONString(consumerStatisticsDTO));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Boolean flag = false;
        BigDecimal serviceMoney;
        statisticsTO.setUpdatedTime(new Date());
        switch (consumerStatisticsDTO.getConsumNotice()) {
            case PAY_SUCCESS:
                //支付成功
                statisticsTO.setPayCount(statisticsTO.getPayCount() + addInt);
                break;
            case REFUND_SUCCESS:
                //退款
                statisticsTO.setRefundMoney(statisticsTO.getRefundMoney().add(consumerStatisticsDTO.getRefundMoney()));
                break;
            case CONSUME_SUCCESS:
                //消费成功
                serviceMoney = statisticsTO.getServiceMoney();
                if (null == serviceMoney) {
                    statisticsTO.setServiceMoney(BigDecimal.ZERO.add(consumerStatisticsDTO.getServiceMoney()));
                } else {
                    statisticsTO.setServiceMoney(statisticsTO.getServiceMoney().add(consumerStatisticsDTO.getServiceMoney()));
                }
                statisticsTO.setServiceTotal(statisticsTO.getServiceTotal() + addInt).setLastTime(sdf.parse(consumerStatisticsDTO.getLastTime()));
                break;
            case CONSUME_START:
                //开始服务 发券通知
                if (null != consumerStatisticsDTO.getCouponId()) {
                    flag = consumerReceiveCoupon(consumerStatisticsDTO.getCouponId(), consumerStatisticsDTO.getId());
                }
                break;
            default:
                throw new InputParamException(InputParamException.Type.INVALID, "传输类型不存在");
        }
        consumerStatisticsService.update(statisticsTO);
        return flag;
    }

    /**
     * 查看是否给老用户发券
     *
     * @param couponId:
     * @param receiveId:
     * @return : java.lang.Boolean
     * @author : gaozifeng
     * @date : 2019/7/13 13:19
     */
    private Boolean consumerReceiveCoupon(Long couponId, Long receiveId) throws Throwable {
        Boolean flag = false;
        ShareReceiveTO newConsumerReceiveInfo = getNewConsumerReceiveInfo(receiveId, couponId);
        if (null != newConsumerReceiveInfo) {
            if (null == newConsumerReceiveInfo.getConsumerCouponId()) {
                flag = true;
            }
        }
        return flag;
    }

    /**
     * 获取新用户领取记录   新用户领取记录是唯一的
     *
     * @param receiveId:
     * @param couponId:
     * @return : com.xingkeduo.pojo.table.ShareReceiveTO
     * @author : gaozifeng
     * @date : 2019/7/13 16:49
     */
    public ShareReceiveTO getNewConsumerReceiveInfo(Long receiveId, Long couponId) throws Throwable {
        List<ShareReceiveTO> shareList = shareReceiveService.selectByQuery(new ShareReceiveQO()
                .setReceiveId(receiveId)
                .setReceiveCouponId(couponId).setIsDelete(YesNoEnum.NO));
        if (null == shareList || shareList.size() == 0) {
            return null;
        }
        return shareList.get(0);
    }

    /**
     * 给老用户发券
     *
     * @param shareReceiveTO:
     * @return : void
     * @author : gaozifeng
     * @date : 2019/7/13 16:52
     */
    public void sendConsumerCoupon(ShareReceiveTO shareReceiveTO, String orderNo) throws Throwable {
        log.info("老用户发券入参shareReceiveTO[{}],orderNo[{}]", JSON.toJSONString(shareReceiveTO), orderNo);
        Map map = feignDomain.bindReceiveAccountOfShareOldUser(shareReceiveTO.getConsumerId());
        log.info("老用户发券Map[{}]", JSON.toJSONString(map));
        if (null == map) {
            throw new DataException(DataException.Type.NULL, "领取记录不能");
        }
        Integer mapId = (Integer) map.get("id");
        long couponId = mapId.longValue();
        Integer couponType = (Integer) map.get("marketingType");
        log.info("老用户发券调用券信息返回couponId[{}],couponType[{}]", couponId, couponType);
        shareReceiveTO.setConsumerCouponId(couponId).setConsumerCouponType(couponType)
                .setOrderNo(Optional.ofNullable(orderNo).orElse(""));
        shareReceiveService.update(shareReceiveTO);
        //TODO 是否发送消息 通知？
    }

    /**
     * 绑定手机号    consumer的
     *
     * @param consumerQO:login
     * @param privateQO:phone
     * @return : void
     * @author : gaozifeng
     * @date : 2019/3/27 14:10
     */
    @Transactional
    public void binding(ConsumerQO consumerQO, ConsumerPrivateQO privateQO) throws Throwable {
        ConsumerTO consumer = getConsumerById(consumerQO);
        ConsumerPrivateTO privateTO = consumerPrivateService.selectByPrimary(consumer.getId());
        if (null == privateTO || privateTO.getId() <= 0)
            throw new DataException(DataException.Type.DEFAULT, "账号信息不存在");

        //手机号查询的
        List<ConsumerPrivateTO> privateList = consumerPrivateService.selectUserPrivateList(privateQO.setIsDelete(YesNoEnum.NO));
        if (null == privateList && privateList.size() <= 0) {
            //新手机没有绑定过
        } else if (privateList.size() == 1) {
            log.info("手机号 已经绑定过其他账号");
            consumer.setfStatus(ConsumerStatusEnums.MERGE);
            if (privateList.get(0).getId() == consumer.getId()) {
                throw new DataException(DataException.Type.DEFAULT, "您已经绑定成功了");
            } else {
                ConsumerTO consumerTO = consumerService.selectByPrimary(privateList.get(0).getId());
                if (consumerTO.getType() == consumer.getType()) {
                    log.info("此手机号已经被其他用户绑定,是" + consumer.getType() + "，类型用户");
                    throw new DataException(DataException.Type.DEFAULT, "手机号已经被其他用户绑定");
                }
            }
            log.info("手机号已经绑定过其他账号,此处标记为合并,是其他第三方登录");
            consumerService.update(consumer);
        } else if (privateList.size() > 1) {
            List<Long> phoneIds = privateList.stream().map(a -> a.getId()).collect(Collectors.toList());
            //手机号的用户集合
            List<ConsumerTO> phoneConsumerList = consumerService.selectConsumerList(new ConsumerQO().setIsDelete(YesNoEnum.NO).setIds(phoneIds));
            log.info("手机号多个绑定账号,查询是否有同一类型---------" + phoneConsumerList.size() + ",个用户集合");
            for (ConsumerTO consumerType : phoneConsumerList) {
                if (consumerType.getId() == consumer.getId()) {
                    throw new DataException(DataException.Type.DEFAULT, "您已经绑定成功了");
                }
                if (consumerType.getType() == consumer.getType()) {
                    throw new DataException(DataException.Type.DEFAULT, "该手机号已经绑定其他账号");
                }
            }
        }
        if (StringUtils.isNotEmpty(privateTO.getPhone())) {
            //有绑定
            //如果手机号绑定了其他微信
            List<ConsumerRelateTO> relateList = relateService.selectConsumerRelateList(new ConsumerRelateQO().setConsumerId(consumer.getId()).setIsDelete(YesNoEnum.NO));
            if (null != relateList && relateList.size() > 0) {
                List<ConsumerRelateTO> updatePhoneList = relateService.selectConsumerRelateList(new ConsumerRelateQO().setPhone(relateList.get(0).getPhone()).setIsDelete(YesNoEnum.NO));
                List<ConsumerRelateTO> update = updatePhoneList.stream().map(a -> a.setIsDelete(YesNoEnum.YES)).collect(Collectors.toList());
                int retVal = relateService.updateList(update);
                if (retVal != update.size()) {
                    throw new DataException(DataException.Type.DEFAULT, "修改用户手机号失败");
                }
                ConsumerPrivateQO phoneQO = new ConsumerPrivateQO();
                phoneQO.setPhone(privateTO.getPhone());
                List<ConsumerPrivateTO> privateTOSList = consumerPrivateService.selectUserPrivateList(phoneQO);
                List<ConsumerPrivateTO> newPhone = privateTOSList.stream().map(a -> a.setPhone(privateQO.getPhone())).collect(Collectors.toList());
                retVal = consumerPrivateService.updateList(newPhone);
                if (retVal != update.size()) {
                    throw new DataException(DataException.Type.DEFAULT, "修改手机号失败");
                }
                List<ConsumerRelateTO> collect = updatePhoneList.stream().map(a -> a.setPhone(privateQO.getPhone())).map(b -> b.setId(IdentityUtil.nextId(Worker.USER))).map(c -> c.setIsDelete(YesNoEnum.NO)).collect(Collectors.toList());
                relateService.insertList(collect);
            } else {
                throw new DataException(DataException.Type.DEFAULT, "无法绑定手机号,没有记录");
            }
        } else {
            privateTO.setPhone(privateQO.getPhone());
            privateTO.setIsDelete(YesNoEnum.NO);
            consumerPrivateService.update(privateTO);
            ConsumerRelateTO consumerRelateTO = new ConsumerRelateTO();
            consumerRelateTO.setPhone(privateQO.getPhone()).setConsumerId(consumer.getId()).setIsDelete(YesNoEnum.NO);
            relateService.insert(consumerRelateTO);
        }
    }


    /**
     * 获取账户手机号列表
     *
     * @param consumerQO:
     * @return : java.util.List<com.xingkeduo.pojo.table.ConsumerRelateTO>
     * @author : gaozifeng
     * @date : 2019/3/28 16:01
     */
    public List<ConsumerRelateTO> getRelateList(ConsumerQO consumerQO) throws Throwable {
        List<ConsumerTO> consumerList = consumerService.selectConsumerList(consumerQO);
        if (null == consumerList || consumerList.size() <= 0)
            throw new DataException(DataException.Type.DEFAULT, "消费者不存在");
        ConsumerPrivateTO privateTO = consumerPrivateService.selectByPrimary(consumerList.get(0).getId());
        if (null == privateTO || privateTO.getId() <= 0)
            throw new DataException(DataException.Type.DEFAULT, "消费私人信息不存在");
        if (StringUtils.isEmpty(privateTO.getPhone())) {
            throw new DataException(DataException.Type.DEFAULT, "尚未绑定手机号");
        }
        return relateService.selectConsumerRelateList(new ConsumerRelateQO().setConsumerId(consumerList.get(0).getId()).setPhone(privateTO.getPhone()).setIsDelete(YesNoEnum.NO));
    }


    /**
     * 获取到店距离
     *
     * @param f_user_id:
     * @param time:
     * @param token:
     * @param mobile_type:
     * @return : java.lang.String
     * @author : pantong
     * @date : 2019/4/15 20:22
     */
    public Map<String, Integer> getUserDistance(long f_user_id, String time, String token, String mobile_type) throws
            Throwable {
        ConsumerTO consumerTO = consumerService.selectByPrimary(f_user_id);
        if (null == consumerTO || consumerTO.getId() <= 0) {
            throw new DataException(DataException.Type.DEFAULT, "用户不存在");
        }
        ConsumerPrivateTO privateTO = consumerPrivateService.selectByPrimary(consumerTO.getId());
        Map<String, Integer> map = new HashMap<String, Integer>();
        map.put("f_frequency", (privateTO == null ? null : privateTO.getDistanceId()));
        return map;
    }

    /**
     * 修改到店距离
     *
     * @param f_user_id:
     * @param time:
     * @param token:
     * @param f_frequency:
     * @param mobile_type:
     * @return : void
     * @author : pantong
     * @date : 2019/4/15 20:06
     */
    public void updateDistance(long f_user_id, String time, String token, int f_frequency, String mobile_type) throws
            Throwable {
        ConsumerTO consumerTO = consumerService.selectByPrimary(f_user_id);
        if (null == consumerTO || consumerTO.getId() <= 0) {
            throw new DataException(DataException.Type.DEFAULT, "用户不存在");
        }
        ConsumerPrivateTO privateTO = consumerPrivateService.selectByPrimary(consumerTO.getId());
        consumerPrivateService.update(privateTO.setDistanceId(f_frequency).setDistance(DistanceEnums.getNameById(f_frequency)));
    }

    /**
     * 发送验证码
     *
     * @param f_user_id:
     * @param f_mobile:
     * @param time:
     * @param token:
     * @param mobile_type:
     * @return : java.lang.String
     * @author : gaozifeng
     * @date : 2019/4/29 19:38
     */
    public Map<String, Object> sendSsm(long f_user_id, String f_mobile, String time, String token, String
            mobile_type) throws Throwable {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        ConsumerTO consumerTO = consumerService.selectByPrimary(f_user_id);
        if (consumerTO.getId() < 0 || null == consumerTO) {
            throw new DataException(DataException.Type.DEFAULT, "用户不存在");
        }
        //可以不要
        ConsumerPrivateTO privateTO = getConsumerPrivateById(consumerTO.getId());
        if (f_mobile.equals(privateTO.getPhone())) {
            throw new DataException(DataException.Type.DEFAULT, "您填写的手机号码已经注册过，请返回修改！");
        }
        ConsumerPrivateQO privateQO = new ConsumerPrivateQO();
        privateQO.setPhone(f_mobile);
        List<ConsumerPrivateTO> consumerPrivateTOS = consumerPrivateService.selectUserPrivateList(privateQO);
        String randomNum = RandomNumberUtil.randonNumForFour();
        if (null == consumerPrivateTOS || consumerPrivateTOS.size() <= 0) {
            //直接发短信
            System.out.println("新用户");
            //is new 0
            feignDomain.sendMsg(SendSmsEnums.USER_UPDATE_PHONE.getType(), f_mobile, randomNum);
            resultMap.put("error", "00");
        } else {
            List<Long> collect = consumerPrivateTOS.stream().map(a -> a.getId()).collect(Collectors.toList());
            List<ConsumerTO> consumerList = consumerService.selectConsumerList(new ConsumerQO().setIds(collect));
            List<ConsumerTO> typeList = consumerList.stream().filter(b -> b.getType() == consumerTO.getType()).collect(Collectors.toList());
            if (null != typeList && typeList.size() > 0) {
                //同一平台绑定过改手机号
                throw new DataException(DataException.Type.DEFAULT, "您填写的手机号码已经注册过，请返回修改！");
            } else {
                //is new 1
                feignDomain.sendMsg(SendSmsEnums.USER_UPDATE_PHONE.getType(), f_mobile, randomNum);
                resultMap.put("error", "01");
            }
        }
        ConsumerSmsTO sms = new ConsumerSmsTO();
        sms.setConsumerId(f_user_id).setPhone(f_mobile).setSmsCode(randomNum).setSmsType("1").setIsDelete(YesNoEnum.NO);
        consumerSmsService.insert(sms);
        return resultMap;
    }

    /**
     * 小程序php绑定手机号码
     *
     * @param f_user_id:
     * @param f_code:
     * @param f_mobile:
     * @param time:
     * @param token:
     * @param mobile_type:
     * @return : java.lang.String
     * @author : gaozifeng
     * @date : 2019/5/2 16:47
     */
    public void bindingPhone(long f_user_id, String f_code, String f_mobile, String time, String token, String
            mobile_type) throws Throwable {
        if (f_user_id <= 0) {
            throw new DataException(DataException.Type.DEFAULT, "用户信息不能为空");
        }
        if (StringUtils.isEmpty(f_code)) {
            throw new DataException(DataException.Type.DEFAULT, "验证码不能为空");
        }
        log.info("php 发送验证码 用户id，" + f_user_id + ",code" + f_code + ",f_mobile" + f_mobile);
        //验证码校验

        if (!RegularUtil.isSelfPhone(f_mobile)) {
            throw new DataException(DataException.Type.DEFAULT, "手机号格式不正确");
        }
        ConsumerTO consumerTO = consumerService.selectByPrimary(f_user_id);
        if (null == consumerTO || consumerTO.getId() <= 0) {
            throw new DataException(DataException.Type.DEFAULT, "用户不存在");
        }
        ConsumerPrivateTO privateTO = consumerPrivateService.selectByPrimary(consumerTO.getId());
        if (null == privateTO || privateTO.getId() <= 0) {
            throw new DataException(DataException.Type.DEFAULT, "用户不存在");
        }
//        if (StringUtils.isNotEmpty(privateTO.getPhone())) {
//            throw new DataException(DataException.Type.DEFAULT, "您已经绑定过手机号");
//        }
        List<ConsumerSmsTO> consumerSmsTOS = consumerSmsService.selectList(new ConsumerSmsQO().setConsumerId(f_user_id).setSmsCode(f_code).setPhone(f_mobile));
        if (null == consumerSmsTOS || consumerSmsTOS.size() <= 0) {
            throw new DataException(DataException.Type.DEFAULT, "手机号或验证码填写不正确");
        }
        feignDomain.checkMsg(SendSmsEnums.USER_UPDATE_PHONE.getType(), f_mobile, f_code);

        ConsumerQO consumerQO = new ConsumerQO();
        consumerQO.setId(f_user_id);
        ConsumerPrivateQO privateQO = new ConsumerPrivateQO();
        privateQO.setPhone(f_mobile);
        binding(consumerQO, privateQO);


//        privateTO.setPhone(f_mobile);
//        consumerPrivateService.update(privateTO);
//        ConsumerRelateTO relateTO = new ConsumerRelateTO();
//        relateTO.setPhone(f_mobile).setConsumerId(f_user_id);
//        relateService.insert(relateTO);
    }

    /**
     * 小程序授权 ,获取code
     *
     * @param js_code:
     * @param mobile_type:
     * @return : java.lang.String
     * @author : gaozifeng
     * @date : 2019/5/8 13:36
     */
    public WxMaCodeDTO code(String js_code, String mobile_type) {
        if (StringUtils.isEmpty(js_code)) {
            throw new DataException(DataException.Type.DEFAULT, "授权信息不能为空");
        }
        if (StringUtils.isEmpty(mobile_type)) {
            throw new DataException(DataException.Type.DEFAULT, "类型不能为空");
        }
//        String code = sendMsgFeign.code(js_code, mobile_type);
//        WxMaCodeDTO wxMaCodeDTO = JSON.parseObject(code, WxMaCodeDTO.class);
//        WxMaCodeDTO wxMaCodeDTO =new WxMaCodeDTO();
//        wxMaCodeDTO.setOpenid("oEEnq0OEEtKODFfXjgrhlSVvGKUU").setUnionid("oRAZ-xK_iyHKfPBonBfNTREVhBtE").setExpiresin("7200").setSessionKey("p01YrXlLqH4cjBfE3IV3BA==");
        WxMaCodeDTO wxMaCodeDTO = feignDomain.consumerCode(js_code, mobile_type);
        log.info("小程序获取的code实体:" + wxMaCodeDTO.toString());
        if (null == wxMaCodeDTO.getSessionKey()) {
            throw new DataException(DataException.Type.DEFAULT, "获取失败");
        }
        return wxMaCodeDTO;
    }

    /**
     * 获取小程序用户信息
     *
     * @param encryptedData:
     * @param f_user_id:
     * @param sessionKey:
     * @param mobile_type:
     * @return : java.lang.String
     * @author : gaozifeng
     * @date : 2019/4/30 16:07
     */
    public BaseDTO getWxUserInfo(String encryptedData, String iv, String sessionKey, long f_user_id, String
            mobile_type) throws Throwable {
        log.info("f_user_id-------------" + f_user_id);
        log.info("-----------------------user------------------encryptedData-------------" + encryptedData);
        BaseDTO baseDTO = new BaseDTO();
        if (f_user_id > 1) {
            log.info("-------不请求--");
            ConsumerTO consumerTO = consumerService.selectByPrimary(f_user_id);
            if (null == consumerTO || consumerTO.getId() <= 0) {
                throw new DataException(DataException.Type.DEFAULT, "用户不存在");
            } else {
                baseDTO.setId(String.valueOf(consumerTO.getId()));
                return baseDTO;
            }
        }
        if (StringUtils.isEmpty(encryptedData) || StringUtils.isEmpty(sessionKey)) {
            log.info("encry------------" + encryptedData);
            log.info("sessionKey------------" + sessionKey);
            throw new DataException(DataException.Type.DEFAULT, "信息格式错误");
        }
        log.info("sessionKey---------------------" + sessionKey);
        log.info("encryptedData---------------------" + encryptedData);
        log.info("iv---------------------" + iv);
        WxMaUserInfo userInfo = feignDomain.getUserInfo(sessionKey, encryptedData, iv);
        log.info("小程序拉取用户信息 userInfo" + userInfo);
        log.info("busseniuser获取小程序拉取用户信息{}-----------------" + userInfo.toString());
        if (null == userInfo.getUnionId()) {
            throw new DataException(DataException.Type.DEFAULT, "小程序拉取用户信息");
        }
        baseDTO.setId(insertConsumerInfo(userInfo));
        return baseDTO;
    }

    /**
     * 根据id查询用户集合
     *
     * @param consumerQO:
     * @return : java.lang.String
     * @author : gaozifeng
     * @date : 2019/5/8 14:01
     */
    public List<Long> getConsumerIds(ConsumerQO consumerQO) throws Throwable {
        ConsumerTO consumerTO = getConsumerById(consumerQO);
        ConsumerPrivateTO privateTO = getConsumerPrivateById(consumerQO.getId());
        List<ConsumerRelateTO> consumerRelateTOS;
        List<Long> list = new ArrayList<>(initListSize);
        if (null != privateTO.getPhone()) {
            consumerRelateTOS = relateService.selectConsumerRelateList(new ConsumerRelateQO().setPhone(privateTO.getPhone()).setIsDelete(YesNoEnum.NO));
            if (null == consumerRelateTOS || consumerRelateTOS.size() <= 0) {
                list.add(consumerTO.getId());
            } else {
                list = consumerRelateTOS.stream().map(a -> a.getConsumerId()).collect(Collectors.toList());
            }
        } else {
            list.add(consumerTO.getId());
        }
        return list;
    }

    /**
     * 查询用户是否存在 传id 不存在返回9004
     *
     * @param f_user_id:
     * @return : java.lang.Long
     * @author : gaozifeng
     * @date : 2019/7/31 18:59
     */
    public Long checkUserExist(Long f_user_id, String mobile_type) throws Throwable {
        if (null == f_user_id || 0L == f_user_id) {
            throw new DataException(DataException.Type.DEFAULT, "账号信息不能为空");
        }
        if (StringUtils.isBlank(mobile_type)) {
            throw new DataException(DataException.Type.DEFAULT, "参数类型不能为空");
        }
        ConsumerTO consumerTO = consumerService.selectByPrimary(f_user_id);
        if (null == consumerTO) {
            throw new DataException(DataException.Type.DEFAULT, "用户不存在");
        }
        ConsumerPrivateTO privateTO = consumerPrivateService.selectByPrimary(f_user_id);
        if (null == privateTO) {
            throw new DataException(DataException.Type.DEFAULT, "用户不存在");
        }
        if ((("wechat").equals(mobile_type) || ("weapp").equals(mobile_type)) && consumerTO.getType() == UserTypeEnums.WX.getType()) {
            return consumerTO.getId();
        }
        if (("alipay").equals(mobile_type) && consumerTO.getType() == UserTypeEnums.ALI.getType()) {
            return consumerTO.getId();
        }
        if (null != privateTO.getPhone()) {
            //绑定手机号要判断双账号问题
            List<Long> privateList = consumerPrivateService.selectUserPrivateForId(new ConsumerPrivateQO().setPhone(privateTO.getPhone()).setIsDelete(YesNoEnum.NO));
            if (privateList.size() >= 1) {
                List<ConsumerTO> consumerList = consumerService.selectConsumerList(new ConsumerQO().setIds(privateList).setIsDelete(YesNoEnum.NO));
                for (ConsumerTO consumer : consumerList) {
                    //TODO 以后增加用户渠道 需要更改
                    if ((("wechat").equals(mobile_type) || ("weapp").equals(mobile_type)) && consumer.getType() == UserTypeEnums.WX.getType()) {
                        consumerTO = consumer;
                        return consumerTO.getId();
                    }
                    if (("alipay").equals(mobile_type) && consumer.getType() == UserTypeEnums.ALI.getType()) {
                        consumerTO = consumer;
                        return consumerTO.getId();
                    }
                }
            }
        }
        throw new DataException(DataException.Type.DEFAULT, "用户不存在");
    }

    /**
     * 获取小程序用户信息
     *
     * @param consumerQO:
     * @return : java.lang.String
     * @author : gaozifeng
     * @date : 2019/5/8 14:01
     */
    public WxMaUserInfo getConsumerInfo(ConsumerPrivateQO queryByOpenid, ConsumerQO consumerQO) throws Throwable {
        if (null == consumerQO.getLogin() && 0 == consumerQO.getId() && null == queryByOpenid.getOpenId() && null == queryByOpenid.getPhone()) {
            throw new DataException(DataException.Type.DEFAULT, "搜索条件不能为空");
        }
        List<Long> userListIds = new ArrayList<>(initListSize);
        if (0 != consumerQO.getId() || null != consumerQO.getLogin()) {
            userListIds.addAll(consumerService.selectConsumerListForid(consumerQO));
        }
        if (null != queryByOpenid.getOpenId()) {
            userListIds.addAll(consumerPrivateService.selectUserPrivateForId(queryByOpenid));
        }
        //查询手机号
        if (null != queryByOpenid.getPhone()) {
            List<ConsumerRelateTO> consumerRelateTOS = relateService.selectConsumerRelateList(new ConsumerRelateQO().setPhone(queryByOpenid.getPhone()));
            userListIds.addAll(consumerRelateTOS.stream().map(a -> a.getConsumerId()).collect(Collectors.toList()));
        }

        if (null == userListIds || userListIds.size() <= 0) {
            log.info("用户不存在------ConsumerPrivateQO[{}],ConsumerQO[{}]", JSON.toJSONString(queryByOpenid), JSON.toJSONString(consumerQO));
            throw new DataException(DataException.Type.DEFAULT, "用户不存在");
        }
        List<ConsumerTO> consumerList = consumerService.selectConsumerList(new ConsumerQO().setIds(userListIds));
        if (null == consumerList || consumerList.size() <= 0) {
            log.info("用户集合为空");
            throw new DataException(DataException.Type.DEFAULT, "用户不存在");
        }
//        ConsumerTO consumerTO = consumerList.get(0);
        ConsumerTO consumerTO = null;
        for (ConsumerTO consumer : consumerList) {
            if (consumer.getType() == UserTypeEnums.WX.getType()) {
                consumerTO = consumer;
            }
        }
        if (null == consumerTO) {
            consumerTO = consumerList.get(0);
        }
        ConsumerPrivateTO privateTO = getConsumerPrivateById(consumerTO.getId());
        WxMaUserInfo wxMaUserInfo = new WxMaUserInfo();
        wxMaUserInfo.setNickName("");
        if (StringUtils.isNotEmpty(consumerTO.getName())) {
            String nickName = Base64Utils.decoderParam(consumerTO.getName());
            log.info("外部调用 getConsumerInfo  解密小程序用户名称nickName[{}]", nickName);
            wxMaUserInfo.setNickName(nickName == null ? "" : nickName);
        } else {
            log.info("外部调用 getConsumerInfo  解密小程序用户名称---用户没有名称----");
        }
        wxMaUserInfo.setCity(String.valueOf(privateTO.getCityId())).setGender(String.valueOf(privateTO.getSex().getValue()))
                .setUnionId(consumerTO.getLogin()).setPhone(null == privateTO.getPhone() ? null : privateTO.getPhone()).setId(String.valueOf(consumerTO.getId())).setMinaOpenId(null == privateTO.getMinaOpenId() ? null : privateTO.getMinaOpenId())
                .setGzhOpenId(null == privateTO.getGzhOpenId() ? null : privateTO.getGzhOpenId());
        //设置aliuser
        if (consumerTO.getType() == UserTypeEnums.ALI.getType()) {
            //TODO 这里如果是支付宝的话 unionId 是支付宝的 不知道有没有影响
            wxMaUserInfo.setAliUserId(consumerTO.getLogin());
        }
        ConsumerFileQO consumerFileQO = new ConsumerFileQO();
        consumerFileQO.setConsumerId(consumerTO.getId());
        consumerFileQO.setType(consumerTO.getType());
        List<ConsumerFileTO> consumerFileTOS = consumerFileService.selectConsumerFileList(consumerFileQO);
        if (null == consumerFileTOS || consumerFileTOS.size() <= 0) {
        } else {
            wxMaUserInfo.setAvatarUrl(consumerFileTOS.get(0).getPath());
        }
        return wxMaUserInfo;
    }

    /**
     * 获取用户信息
     *
     * @param consumerQO:
     * @return : com.xingkeduo.pojo.table.ConsumerTO
     * @author : gaozifeng
     * @date : 2019/5/9 20:13
     */
    private ConsumerTO getConsumerById(ConsumerQO consumerQO) throws Throwable {
        ConsumerTO consumerTO = consumerService.selectByPrimary(consumerQO.getId());
        if (null == consumerTO || consumerTO.getId() <= 0) {
            throw new DataException(DataException.Type.DEFAULT, "用户不存在");
        }
        return consumerTO;
    }

    /**
     * 获取用户信息
     *
     * @return : com.xingkeduo.pojo.table.ConsumerTO
     * @author : gaozifeng
     * @date : 2019/5/9 20:13
     */
    private ConsumerPrivateTO getConsumerPrivateById(long id) throws Throwable {
        ConsumerPrivateTO privateTO = consumerPrivateService.selectByPrimary(id);
        if (null == privateTO || privateTO.getId() <= 0) {
            throw new DataException(DataException.Type.DEFAULT, "用户信息不存在");
        }
        log.info("private 信息  --------" + JSON.toJSONString(privateTO));
        return privateTO;
    }


    /**
     * 获取用户私人信息
     *
     * @param consumerPrivateQO
     * @return
     * @throws Throwable
     */
    public ConsumerPrivateTO getConsumerPrivate(ConsumerPrivateQO consumerPrivateQO) throws Throwable {
        ConsumerPrivateTO privateTO = consumerPrivateService.selectByPrimary(consumerPrivateQO.getId());
        if (null == privateTO || privateTO.getId() <= 0) {
            throw new DataException(DataException.Type.DEFAULT, "用户信息不存在");
        }
        return privateTO;
    }
}
